package com.notification.yftech.yf_notification;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "yftech notify";
    EditText textSendTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * andriod 6.0以上动态获取权限的方式
         */
        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
            if(this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
            }
        }

        Button sendNotice = findViewById(R.id.btn_send);
        sendNotice.setOnClickListener(this); //绑定按钮时间监听
        textSendTime = findViewById(R.id.editTextTime);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    void sendNotification(NotificationManager manager, PendingIntent pendingIntent, int sendCount, String notificationText) {
        for (int i = 1; i < sendCount + 1; i++) {
            try {
                //设置多少秒推送一次
                if (!textSendTime.getText().toString().equals("")) {
                    int time = Integer.parseInt(textSendTime.getText().toString());
                    Log.d(TAG, "sendNotification: time is " + time);
                    Thread.sleep(time * 1000);
                } else {
                    Thread.sleep(1000);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("第" + i + "条消息")
                    .setContentText(notificationText)
                    .setWhen(System.currentTimeMillis())
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText))
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .build();
            if (manager != null) {
                manager.notify(1, notification);
            }
        }
    }

    //发送随机汉字
    void sendNotification(NotificationManager manager, PendingIntent pendingIntent, int sendCount, int jinhanLen) {
        for (int i = 1; i < sendCount + 1; i++) {
            try {
                //设置多少秒推送一次
                if (!textSendTime.getText().toString().equals("")) {
                    int time = Integer.parseInt(textSendTime.getText().toString());
                    Log.d(TAG, "sendNotification: time is " + time);
                    Thread.sleep(time * 1000);
                } else {
                    Thread.sleep(1000);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String notificationText = getNotificationText(jinhanLen);
            Log.d(TAG, "sendNotification: " + notificationText);

            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("第" + i + "条消息")
                    .setContentText(notificationText)
                    .setWhen(System.currentTimeMillis())
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText))
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .build();
            if (manager != null) {
                manager.notify(1, notification);
            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                EditText notifyNumber = findViewById(R.id.notify_num);
                EditText jinhanLen = findViewById(R.id.jinhan_len);
                EditText notifyText = findViewById(R.id.notification_text);
                CheckBox checkBox = findViewById(R.id.checkbox_jinhan);
                int text_len = Integer.parseInt(jinhanLen.getText().toString());       //随机汉字长度

                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Intent intent = new Intent(this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

                if (!notifyNumber.getText().toString().equals("")) {
                    int send_count = Integer.parseInt(notifyNumber.getText().toString());  //发送消息次数
                    if (checkBox.isChecked()) {
                        Log.d(TAG, "onClick: 使用随机汉字");
                        sendNotification(manager, pendingIntent, send_count, text_len);
                    } else {
                        Log.d(TAG, "onClick: 使用自定义消息内容");
                        if (!notifyText.getText().toString().equals("")) {
                            Log.d(TAG, "推送消息: " + notifyText.getText().toString());
                            sendNotification(manager, pendingIntent, send_count, notifyText.getText().toString());
                        } else {
                            Toast.makeText(this, "消息提醒正文不能为空", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(this, "消息提醒次数不能为空", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }
    }

    //随机生成常见汉字
    public static String getRandomChar() {
        String str = "";
        int highCode;
        int lowCode;

        Random random = new Random();

        highCode = (176 + Math.abs(random.nextInt(39))); //B0 + 0~39(16~55) 一级汉字所占区
        lowCode = (161 + Math.abs(random.nextInt(93))); //A1 + 0~93 每区有94个汉字

        byte[] b = new byte[2];
        b[0] = (Integer.valueOf(highCode)).byteValue();
        b[1] = (Integer.valueOf(lowCode)).byteValue();

        try {
            str = new String(b, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    public String getNotificationText(int len) {
        String notification = "";
        for (int i = 0; i < len; i++) {
            notification += getRandomChar();
        }
        return notification;
    }
}
